package org.ayachinene.leetcode.utils;

import org.ayachinene.leetcode.structure.ListNode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.util.CollectionUtils;

import java.util.List;

public class ListUtils {

    public static @Nullable ListNode getList(@NotNull String s) {
        List<String> elementStrings = CommonUtils.extract(s);
        if (CollectionUtils.isEmpty(elementStrings)) {
            return null;
        }
        ListNode l = new ListNode(Integer.parseInt(elementStrings.get(0)));
        final ListNode[] tail = {l};
        elementStrings.subList(1, elementStrings.size())
                .forEach(elementString -> {
                    tail[0].next = new ListNode(Integer.parseInt(elementString));
                    tail[0] = tail[0].next;
                });
        return l;
    }

    public static boolean listEquals(@Nullable ListNode l1, @Nullable ListNode l2) {
        if (l1 == null)
            return l2 == null;
        if (l2 == null)
            return false;

        ListNode p1 = l1;
        ListNode p2 = l2;
        while (p1 != null && p2 != null) {
            if (p1.val != p2.val) {
                return false;
            }
            p1 = p1.next;
            p2 = p2.next;
        }
        return p1 == p2;
    }
}
